package com.air.db;

import com.air.tools.PropertiesTools;
import com.air.tools.output;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 *  数据库链接 工具,管理数据库连接的
 * @author air
 * @since v1
 * @date 2018年11月21日12:54:59
 */
public class DbConnectionFactory {
	/**
	 * 获取一个数据库链接
	 * @return 如果已经超出了 最大连接数 就从第0个获得连接开始获取 连接 不停循环
	 */
	public static Connection getConnection() {
        PropertiesTools pro = PropertiesTools.getInstance();
        String driver = pro.getJdbcClass(pro.getDbType());
        String url = pro.getDbUrl();
        String user = pro.getDbUser();
        String pass = pro.getDbPass();
		return getConnection(url, user, pass, driver);
	}

	public static synchronized Connection getConnection(String url, String user,String pass, String driver){
        if(dbConnectionPool.size() > max){
            if(now > max){
                now = 0;
            }
            return dbConnectionPool.get(now++);
        }
        Connection con = null;
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url, user, pass);
            dbConnectionPool.add(con);
            return dbConnectionPool.get(now++);
        } catch (Exception e) {
            output.outLine(e.toString());
            e.printStackTrace();
            return null;
        }
    }
	private DbConnectionFactory() { }

    /**
     * 设置最大链接数量
     * @param max
     */
	public static void setMax(int max){
		DbConnectionFactory.max = max;
	}

    /**
     * 关闭所有连接
     */
	public void closeDBAll(){
        dbConnectionPool.stream().forEach(e -> {
            try {
                e.close();
            } catch (SQLException e1) {
                output.outLine(e1.toString());
            }
        });
        dbConnectionPool.clear();
        now = 0;
    }
	private static List<Connection> dbConnectionPool = new LinkedList<>();
	private static int max = 50;
	private static int now = 0;
}
